package xyz.hubery.controller;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.hubery.model.BaseResult;
import xyz.hubery.pojo.Orders;
import xyz.hubery.pojo.Payment;
import xyz.hubery.service.OrdersService;
import xyz.hubery.service.ZfbPayService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 支付
 */
@Slf4j
@RestController
@RequestMapping("/user/payment")
public class PaymentController {
    @DubboReference(timeout = 15000)
    private ZfbPayService zfbPayService;
    @DubboReference
    private OrdersService ordersService;


    /**
     * 生成二维码
     *
     * @param orderId 订单号
     * @return 二维码url
     */
    @PostMapping("/pcPay")
    public BaseResult<String> pcPay(String orderId) {
//        return BaseResult.ok("https://qr.alipay.com/bax08221kl4jixrcouxd0053");
        Orders orders = ordersService.findById(orderId);
        String codeUrl = zfbPayService.pcPay(orders);
        return BaseResult.ok(codeUrl);
    }


    /**
     * 支付成功的回调方法，用户扫码支付后支付宝调用的
     *
     * @param request
     * @return
     */
    @PostMapping("/success/notify")
    public BaseResult successNotify(HttpServletRequest request) {
        log.info("支付成功回调方法");
        // 1.验签
        Map<String, String[]> parameterMap = request.getParameterMap();
        // 新Map
        Map<String, String[]> newMap = new HashMap<>(parameterMap);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestParameterMap", newMap);
        zfbPayService.checkSign(paramMap);

        String trade_status = request.getParameter("trade_status");// 订单状态
        String out_trade_no = request.getParameter("out_trade_no");// 订单编号
        // 如果支付成功
        if (trade_status.equals("TRADE_SUCCESS")) {
            // 2.修改订单状态
            Orders orders = ordersService.findById(out_trade_no);
            orders.setStatus(2); // 订单状态为已付款
            orders.setPaymentType(2);// 支付宝支付
            orders.setPaymentTime(new Date());
            ordersService.update(orders);


            // 3.添加交易记录
            // 异步调用支付服务（可重试）
            CompletableFuture.runAsync(() -> {
                retryCreatePayment(out_trade_no,trade_status, orders.getPayment(), JSON.toJSONString(request.getParameterMap()));
            });
        }
        return BaseResult.ok();
    }


    /**
     * 重试添加交易记录
     */
    private void retryCreatePayment(String outTradeNo, String tradeStatus, BigDecimal mum, String desc) {
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.execute(context -> {
            log.info("添加交易记录");
            try{
                Payment payment = new Payment();
                payment.setOrderId(outTradeNo); // 订单编号
                payment.setTransactionId(outTradeNo); // 交易号
                payment.setTradeType("支付宝支付"); // 交易类型
                payment.setTradeState(tradeStatus); // 交易状态
                payment.setPayerTotal(mum); // 付款金额
                payment.setContent(JSON.toJSONString(desc)); // 支付详情
                payment.setCreateTime(new Date()); // 支付时间
                zfbPayService.addPayment(payment);
                return true;
            }catch (Exception e) {
                log.warn("第{}次创建支付记录失败", context.getRetryCount());
                if (context.getRetryCount() >= 3) {
                    // 记录失败，等待人工干预或对账
//                    alertService.sendAlert("支付记录创建失败: " + outTradeNo);
                }
                throw e;
            }
        });
    }


//    @Scheduled(cron = "0 0/10 * * * ?")
//    public void reconcileProcess() {
//        // 查询已更新但无支付记录的订单
//        List<String> abnormalOrders = ordersService.findOrdersWithoutPayment();
//        for (String orderNo : abnormalOrders) {
//            try {
//                // 重新创建支付记录
//                zfbPayService.compensatePayment(orderNo);
//            } catch (Exception e) {
//                log.error("补偿支付记录失败: {}", orderNo, e);
//            }
//        }
//    }


}
